package com.wn.access.utils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Base64;

public class EncodeUtil {

    /**
     * 对字符串进行加密操作
     * @param str
     * @return
     */
    public static String encodeBase64(String str){
        String encoded = null;
        try {
            encoded = Base64.getEncoder().encodeToString(str.getBytes("utf-8"));

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return encoded;

    }

    /**
     * 解密
     * @param str
     * @return
     */
    public static String decodeBase64(String str){
        String decoded = null;
        byte[] bytes = Base64.getDecoder().decode(str);
        try {
            decoded = new String(bytes,"utf-8");
        }catch(UnsupportedEncodingException e){
            e.printStackTrace();
        }
        return decoded;
    }

    public static String encodeURL(String url) {
    	String encoded = null;
		try {
			encoded =  URLEncoder.encode(url, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return encoded;
	}

	public static String decodeURL(String url) {
    	String decoded = null;
		try {
			decoded = URLDecoder.decode(url, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return decoded;
	}

    public static void main(String[] args) {
        //加密
        String hello_abc = EncodeUtil.encodeBase64("hello abc");
        System.out.println("hello_abc = " + hello_abc);

        //解析
        String s = EncodeUtil.decodeBase64(hello_abc);
        System.out.println("s = " + s);

    }
}
